package wiki.zimo.certificate_manage.controller;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import wiki.zimo.certificate_manage.constant.Constant;
import wiki.zimo.certificate_manage.dao.MajorDao;
import wiki.zimo.certificate_manage.dao.SchoolDao;
import wiki.zimo.certificate_manage.dao.StudentDao;
import wiki.zimo.certificate_manage.dao.TeacherDao;
import wiki.zimo.certificate_manage.domain.*;
import wiki.zimo.certificate_manage.service.ExcelService;
import wiki.zimo.certificate_manage.service.FileSaveService;
import wiki.zimo.certificate_manage.utils.UUIDUtils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 子墨
 * @date 2018/10/23 15:05
 * @describe 处理学生
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private MajorDao majorDao;
    @Autowired
    private SchoolDao schoolDao;
    @Autowired
    private ExcelService excelService;

    @Autowired
    private FileSaveService fileSaveService;


    /**
     * 新增页
     * @author 子墨
     * @date 2018/10/19 10:37
     * @params []
     * @return java.lang.String
     */
    @RequestMapping(value = "add")
    public String add(Map<String,Object> map){
        Sort sort = new Sort(Sort.Direction.ASC, "majorName");
        List<Major> majors = majorDao.findAll(sort);
        List<School> schools = schoolDao.findAll();
        List<Teacher> teachers = teacherDao.findAll();
        map.put("majors",majors);
        map.put("schools",schools);
        map.put("teachers",teachers);
        return "student/add";
    }

    /**
     * 列表页
     * @author 子墨
     * @date 2018/10/19 10:38
     * @params []
     * @return java.lang.String
     */
    @RequestMapping(value = "list")
    public String list(){
        return "student/list";
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/28 17:24
     * @describe: excel 页
     * @param: []
     * @return: java.lang.String
     * @version v1.0
     */
    @RequestMapping(value = "excel")
    public String excel(){
        return "student/upload";
    }

    /**
     * 更新页
     * @author 子墨
     * @date 2018/10/19 15:03
     * @params [map, id]
     * @return java.lang.String
     */
    @RequestMapping(value = "update")
    public String update(Map<String,Object> map,
                         @RequestParam(value = "id",required = true)String id){
        Student student = studentDao.findStudentById(id);
        map.put("student",student);
        return add(map);
    }

    /**
     * 一键导出Excel数据
     * @author 子墨
     * @date 2018/10/19 15:09
     * @params [response]
     * @return void
     */
    @RequestMapping(value = "/export")
    public void exportExcel(HttpServletResponse response,HttpSession session) {
        List<Student> list = new ArrayList<>();
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return;
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_LEADER:
                list = studentDao.findAll();
                break;
            case Constant.ROLE_TEACHER:
                list = studentDao.findAllByTeacherId(user.getTeacher().getId());
                break;
            case Constant.ROLE_STUDENT:
                list.add(user.getStudent());
                break;
        }
        System.out.println(list.toString());
        // 指定列表标题和工作表名称
        ExportParams params = new ExportParams("学生信息","学生信息表");
        try {
            excelService.doExportExcel(response,list,Student.class,params,"学生信息表");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 新增或者修改学生信息接口
     * @author 子墨
     * @date 2018/10/18 22:53
     * @params [map, id, schoolName]
     * @return wiki.zimo.certificate_manage.domain.Student
     */
    @RequestMapping(value = "/addStudent")
    @ResponseBody
    public Student addStudent(Map<String,Object> map,
                              @RequestParam(value = "id",required = false)String id,
                              @RequestParam(value = "studentNum",required = true)String studentNum,
                              @RequestParam(value = "studentPassword",required = false,defaultValue = "123456")String studentPassword,
                              @RequestParam(value = "studentName",required = true)String studentName,
                              @RequestParam(value = "studentTel",required = true)String studentTel,
                              @RequestParam(value = "studentEmail",required = false)String studentEmail,
                              @RequestParam(value = "studentMajorAndClass",required = true)String studentMajorAndClass,
                              @RequestParam(value = "teacherId",required = true)String teacherId,
                              @RequestParam(value = "studentSchool",required = true) String studentSchool){
        if (id == null || id.replaceAll(" ","").equals("")){
            Student student = new Student();
            student.setId(UUIDUtils.getRandomID());
            student.setStuNum(studentNum);
            if ( ! studentPassword.replaceAll(" ","").equals("")){
                student.setStuPassword(studentPassword);
            }else {
                student.setStuPassword(Constant.DEFAULT_PASSWORD);
            }
            student.setStuName(studentName);
            student.setStuTellphone(studentTel);
            student.setStuEmail(studentEmail);
            String[] arr = studentMajorAndClass.split("-");
            student.setStuMajor(arr[0]);
            student.setStuClass(arr[1]);
            student.setStuSchool(studentSchool);
            student.setTeacherId(teacherId);
            return studentDao.save(student);
        }
        Student student = studentDao.findStudentById(id);
        student.setStuNum(studentNum);
        if ( ! studentPassword.replaceAll(" ","").equals("")){
            student.setStuPassword(studentPassword);
        }else {
            student.setStuPassword(Constant.DEFAULT_PASSWORD);
        }
        student.setStuName(studentName);
        student.setStuTellphone(studentTel);
        student.setStuEmail(studentEmail);
        String[] arr = studentMajorAndClass.split("-");
        student.setStuMajor(arr[0]);
        student.setStuClass(arr[1]);
        student.setStuSchool(studentSchool);
        student.setTeacherId(teacherId);
        return studentDao.save(student);
    }

    /**
     * 得到所有学生信息接口
     * @author 子墨
     * @date 2018/10/19 12:38
     * @params []
     * @return java.util.List<wiki.zimo.certificate_manage.domain.Student>
     */
    @RequestMapping(value = "/getAllStudent")
    @ResponseBody
    public List<Student> getAllStudent(HttpSession session){
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return null;
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_TEACHER:
                return studentDao.findStudentsByTeacherId(user.getTeacher().getId());
            case Constant.ROLE_STUDENT:
                List<Student> students = new ArrayList<>();
                students.add(studentDao.findStudentById(user.getStudent().getId()));
                return students;
        }
        return studentDao.findAll();
    }

    /**
     * 删除学生信息接口
     * @author 子墨
     * @date 2018/10/19 14:11
     * @params [id]
     * @return java.lang.String
     */
    @RequestMapping(value = "delete")
    public String delete(Map<String,Object> map,
                         @RequestParam(value = "id")String id){
        if (studentDao.existsById(id)){
            studentDao.deleteById(id);
        }
        map.put(Constant.MSG,"提示：删除成功");
        return list();
    }
    
    /**
     * @auther: 子墨
     * @date: 2018/10/28 17:28
     * @describe: 文件上传接口
     * @param: [file]
     * @return: java.lang.String
     * @version v1.0
     */
    @RequestMapping(value = "upload")
    @ResponseBody
    public String upload(@RequestParam(value = "file")MultipartFile file){
        String fileName = fileSaveService.savaFile(file);

        try {
            List<Student> students = excelService.doImportExcel(fileName,Student.class,new ImportParams());
            for (Student s:students){
                s.setStuPassword("123456");
            }
            studentDao.saveAll(students);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }
}
